/* eslint-disable react/no-unused-state */
import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import DataSet from '@antv/data-set';
import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Button,
  Table,
  Menu,
  Dropdown,
  Divider,
  Modal,
  message,
} from 'antd';
import { Chart, Geom, Coord } from 'bizcharts';
import { DownOutlined } from '@ant-design/icons';

import AddOrDelInfo from './components/addOrDel';
import temperature from '../../../../../../public/temperature.png';
import humidity from '../../../../../../public/humidity.png';

import styles from './index.less';
import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { DataView } = DataSet;
const { confirm } = Modal;
const { Item } = Menu;
const { pathname } = window.location;

const modalTypeText = [
  ['置空闲', 'cell_updateCellIdle'],
  ['置预定', 'cell_updateCellBooked'],
  ['置故障', 'cell_updateCellGlitch'],
];

const transform = {
  type: 'percent',
  field: 'count',
  dimension: 'item',
  as: 'percent',
};

interface MouthDetailProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  orderVisible: boolean;
  cellTypeList: any;
  statusList: any;
  detailInfo: any;
  lastInfo: any;
  unfinishedOrder: string;
  location: { query: any };
}

interface MouthDetailState {
  searchValues: any;
  modalVisible: boolean;
  modalType: number;
  setId: number;
  descVisible: boolean;
  openVisible: boolean;
  openCellId: number;
  addOrDelVisible: boolean;
  addOrDelType: number;
  rowId:number;
  selectedRowKeys:any[];
}

@connect(
  ({
    mouthDetailsList: {
      dataInfo,
      orderVisible,
      cellTypeList,
      statusList,
      detailInfo,
      lastInfo,
      unfinishedOrder,
    },
    loading,
  }: any) => ({
    dataInfo,
    orderVisible,
    cellTypeList,
    statusList,
    detailInfo,
    lastInfo,
    unfinishedOrder,
    loading: loading.effects['mouthDetailsList/fetch'],
  }),
)
class MouthDetailElem extends Component<MouthDetailProps, MouthDetailState> {
  columns: any = [
    { title: '格口编号', dataIndex: 'code' },
    { title: '描述', dataIndex: 'desc' },
    { title: '格口类型', dataIndex: 'typeName' },
    { title: '服务类型', dataIndex: 'serviceType' },
    { title: '格口状态', dataIndex: 'statusName' },
    { title: '占用类型', dataIndex: 'occupyTypeName' },
    { title: '格口长度', dataIndex: 'length' },
    { title: '格口宽度', dataIndex: 'width' },
    { title: '格口高度', dataIndex: 'height' },
    { title: '操作人', dataIndex: 'updateUserName' },
    {
      title: '操作',
      dataIndex: 'id',
      fixed: 'right',
      width: 150,
      render: (text: number, row: any) => (
        <div>
          <span className="operLink" onClick={() => this.handleOpenCellShowModal(true, text)}>
            打开格口
          </span>
          <Divider type="vertical" />
          <Dropdown arrow overlay={() => this.menu(row)}>
            <span className="operLink">
              更多 <DownOutlined />
            </span>
          </Dropdown>
        </div>
      ),
    },
  ];

  state: MouthDetailState = {
    searchValues: {
      cabinetId: 0,
      desc: '',
      code: '',
      status: '',
      serviceType: '',
      type: '',
      pageIndex: 1,
      pageSize: 20,
    },
    modalVisible: false,
    modalType: 0,
    setId: 0,
    descVisible: false,
    openVisible: false,
    openCellId: 0,
    addOrDelVisible: false,
    addOrDelType: 1,
    rowId: 0,
    selectedRowKeys: [],
  };

  rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
      this.setState({ selectedRowKeys });
    },
  }

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...values } = query;
    if (query && query.id) {
      return {
        searchValues: {
          ...values,
          cabinetId: query.id,
          pageIndex: Number(pageIndex) || 1,
          pageSize: Number(pageSize) || 20,
        },
      };
    }
    return null;
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchDataValues();
    this.fetchAction('fetchCellType');
    this.fetchAction('fetchStatus');

    const { location: { query: { id } } } = this.props;
    this.fetchAction('fetchDetail', { id });
    this.fetchAction('fetchLastInfo', { cabinetId: id });
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues } = this.state;
    const { location: { query: { id } } } = this.props;
    if (!_.isEqual(searchValues, prevState.searchValues) || id !== prevProps.location.query.id) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const {
      searchValues: {
        pageIndex,
        pageSize,
        cabCode,
        id,
        name,
        cabinetId,
        ...values
      },
    } = this.state;
    const params = this.turnValuesType(values);

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(params);
  };

  turnValuesType = (values: any) => ({
    // 转换数据类型
    ...values,
    serviceType: Number(values.serviceType) || '',
  });

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues } = this.state;
    return searchValues;
  };

  menu = (row: any) => {
    const {
      location: { query },
    } = this.props;
    return (
      <Menu>
        <Item className="operLink" onClick={() => this.handleShowModal(true, 0, row.id)}>
          置空闲
        </Item>
        <Item className="operLink" onClick={() => this.handleShowModal(true, 1, row.id)}>
          置预定
        </Item>
        <Item className="operLink" onClick={() => this.handleShowModal(true, 2, row.id)}>
          置故障
        </Item>
        <Item className="operLink" onClick={() => this.handleRouterCellTrajectory(row.code, query.cabCode)}>
          格口轨迹
        </Item>
        <Item className="operLink" onClick={() => this.handleRouterHistoryOrder(query, row)}>
          历史订单
        </Item>
        <Item className="operLink" onClick={() => this.handleRouterLogs(row)}>
          操作日志
        </Item>
      </Menu>
    );
  };

  // 格口轨迹
  handleRouterCellTrajectory = (code: string, cabCode: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `格口${code}轨迹`,
      url: `/basic/cabinetManagement/list/mouthDetails/trajectory?cellCode=${code}&cabCode=${cabCode}`,
    });
  };

  // 历史订单
  handleRouterHistoryOrder = (query: any, row: any) => {
    const params = {
      cabinetName: query.name,
      cabinetCode: query.cabCode,
      cellId: row.id,
      cellCode: row.code,
      cellType: row.typeName,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `格口${row.code}订单`,
      url: `/basic/cabinetManagement/list/mouthDetails/historyOrder?${qs.stringify(params)}`,
    });
  };

  // 操作日志
  handleRouterLogs = (record: any) => {
    const params = {
      cabId: record.cabinetId,
      cellId: record.id,
      cellCode: record.code,
    };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `格口${record.code}日志`,
      url: `/basic/cabinetManagement/list/mouthDetails/log?${qs.stringify(params)}`,
    });
  };

  handleShowModal = (modalVisible: boolean, modalType: number, cellId: number = 0) => {
    const { setId } = this.state;
    this.setState({ modalVisible, modalType, setId: cellId || setId });
  };

  handleConfirm = () => {
    const { searchValues, setId, modalType } = this.state;
    const params = {
      search: searchValues,
      cellId: setId,
      type: modalTypeText[modalType][1],
    };
    this.fetchAction('checkMouth', params);
    this.handleShowModal(false, modalType);
  };

  handleChangeDescModal = (descVisible: boolean) => {
    this.setState({ descVisible });
  };

  // 批量置空闲
  batchLeisure = () => {
    const { selectedRowKeys, searchValues } = this.state;
    if (!selectedRowKeys.length) {
      message.error('请选择对应的格口');
      return;
    }

    const _this = this;
    confirm({
      title: '提示',
      content: '确认置空闲？',
      okText: '确认',
      onOk() {
        _this.fetchAction('updateCellIdle', {
          search: searchValues,
          cellIds: selectedRowKeys.join(','),
        });
      },
    });
  }

  handleConfimchanfgeDesc = () => {
    const { searchValues: search } = this.state;
    const { location: { query: { id: cabinetId } } } = this.props;

    const params = { search, cabinetId };
    this.fetchAction('changeDesc', params);
    this.handleChangeDescModal(false);
  };

  handleSetIdle = () => {
    // 确定置空闲
    const { searchValues, setId } = this.state;
    const params = {
      search: searchValues,
      cellId: setId,
      type: modalTypeText[0][1],
    };
    this.fetchAction('setMouth', params);
    this.fetchAction('orderStatus', { body: true });
  };

  handleOpenCellShowModal = (openVisible: boolean, openCellId: number = 0) => {
    this.setState({ openVisible, openCellId });
  };

  handleConfirmOpenCall = () => {
    const { searchValues, openCellId: cellId } = this.state;
    const params = { search: searchValues, cellId };
    this.fetchAction('openCell', params);
    this.handleOpenCellShowModal(false);
  };

  handleShowAddOrDelModal = (addOrDelVisible: boolean, addOrDelType: number) => {
    this.setState({ addOrDelVisible, addOrDelType });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { location: { query } } = this.props;
      const params = {
        ...query,
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: `查看${query.name}格口`,
        url: `${pathname}?${qs.stringify(params)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { location: { query: { cabCode, id, name } } } = this.props;
    const params = { cabCode, id, name };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${name}格口`,
      url: `${pathname}?${qs.stringify(params)}`,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const { location: { query } } = this.props;
    const params = {
      ...searchValues,
      ...query,
      pageIndex,
      pageSize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${query.name}格口`,
      url: `${pathname}?${qs.stringify(params)}`,
      isTopMenu: true,
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = `mouthDetailsList/${typeName}`;
    if (type.indexOf('addOrUpdateSet') >= 0) {
      const { searchValues } = this.state;
      const { location: { query: { id: detailId } } } = this.props;
      const search = {
        ...searchValues,
        pageIndex: 1,
        pageSize: 20,
      };
      payload = { ...payload, search, detailId };
    }

    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  handleHumiture = () => {
    const {
      dispatch,
      location: { query: { id } },
    } = this.props;
    addTab(dispatch, {
      name: '温湿度历史数据',
      url: `/basic/cabinetManagement/list/mouthDetails/humiture?id=${id}`,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }


  render() {
    const data = [
      { item: '事例一', count: 80 },
      { item: '事例二', count: 220 },
    ];
    const dv = new DataView();
    dv.source(data).transform(transform);

    const {
      searchValues: { pageIndex, pageSize },
      modalVisible,
      modalType,
      descVisible,
      openVisible,
      addOrDelVisible,
      addOrDelType,
    } = this.state;

    const {
      form: { getFieldDecorator },
      dataInfo,
      orderVisible,
      cellTypeList,
      statusList,
      detailInfo,
      lastInfo,
      unfinishedOrder,
      location: { query },
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    const is_Low_version = detailInfo.hwareVersion === '1.0'
      || detailInfo.hwareVersion === '2.0'
      || detailInfo.hwareVersion === '2.7'
      || detailInfo.hwareVersion === '3.0'
      || detailInfo.hwareVersion === '4.0'
      || detailInfo.hwareVersion === '4.1'
      ? 0 : 1;

    return (
      <Fragment>
        <PageHeader />

        {query.isCollection === '1' && (
          <Card
            title="当前主柜温湿度"
            bordered={false}
            extra={
              <Button type="primary" onClick={this.handleHumiture}>
                温湿度历史数据
              </Button>
            }
          >
            <div style={{ display: 'flex', padding: '8px 0' }}>
              <div>
                温度范围：<span style={{ color: '#FA9014' }}>-40~120 ℃</span>
              </div>
              <div style={{ marginLeft: 20 }}>
                湿度范围：<span style={{ color: '#19B2ED' }}>0~100% RH</span>
              </div>
            </div>

            <div style={{ display: 'flex', marginTop: 10 }}>
              <div>
                <div className={styles.temperature}>
                  <img src={temperature} style={{ width: 14, height: 22 }} alt="" />
                  <span style={{ marginLeft: 6 }}>温度</span>
                  <span style={{ marginLeft: 10 }}>{lastInfo.temperature} ℃</span>
                </div>
                {lastInfo.temperature >= 42 && (
                  <div
                    style={{
                      textAlign: 'center',
                      marginTop: 10,
                      fontSize: 12,
                      color: 'red',
                    }}
                  >
                    当前温度过高，请检查风扇是否已正常启动
                  </div>
                )}
              </div>
              <div>
                <div className={styles.humidity}>
                  <img src={humidity} style={{ width: 20, height: 20 }} alt="" />
                  <span style={{ marginLeft: 6 }}>湿度</span>
                  <span style={{ marginLeft: 10 }}>{lastInfo.humidity}% RH</span>
                </div>
                {lastInfo.temperature >= 42 && <div style={{ marginTop: 10 }} />}
              </div>
            </div>
          </Card>
        )}

        <Card title={`设备编号:${query.cabCode}`} bordered={false}>
          <Row gutter={12}>
            {dataInfo.cellCount.map((item: any, index: number) => (
              <Col
                md={4}
                span={12}
                key={item[0]}
                className="marginT20"
                style={index !== 5 && index !== 11 ? { borderRight: '1px solid #eee' } : {}}
              >
                <h4 className={styles.codeName}>{item[1].describe}</h4>
                <Chart
                  height={60}
                  data={new DataView()
                    .source([
                      { item: '事例一', count: item[1].free || 0 },
                      { item: '事例二', count: (item[1].count || 1) - (item[1].free || 0) },
                    ])
                    .transform(transform)}
                  forceFit
                  padding={[0, 10, 0, 10]}
                >
                  <Coord type="theta" innerRadius={0.7} />
                  <Geom
                    type="intervalStack"
                    position="percent"
                    color={['item', ['#FAAD14', '#e0e0e0']]}
                  />
                </Chart>
                <div className="marginT16">
                  总数: <span className={styles.codeNumber}>{item[1].count}</span>
                  <span className="marginL8">
                    闲置: <span className={styles.codeNumber}>{item[1].free}</span>
                  </span>
                </div>
              </Col>
            ))}
          </Row>
        </Card>

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Form.Item label="格口简称">
                  {getFieldDecorator('desc')(<Input allowClear placeholder="请输入" />)}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="格口状态">
                  {getFieldDecorator('status')(
                    <Select allowClear placeholder="请选择">
                      {statusList.map((item: any) => (
                        <Option value={item.key} key={item.key}>
                          {item.value}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="服务类型">
                  {getFieldDecorator('serviceType')(
                    <Select allowClear placeholder="请选择">
                      <Option value={1}>快递</Option>
                      <Option value={2}>信报</Option>
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="格口编号">
                  {getFieldDecorator('code')(
                    <Input allowClear type="number" placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={12} justify="space-between">
              <Col md={6} sm={24}>
                <Form.Item label="格口类型">
                  {getFieldDecorator('type')(
                    <Select allowClear placeholder="请选择">
                      {cellTypeList.map((item: any) => (
                        <Option value={item.key} key={item.key}>
                          {item.value}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={() => this.handleChangeDescModal(true)}
            >
              修改格口描述
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginL8"
              onClick={() => this.batchLeisure()}
            >
              批量置空闲
            </Button>
            {is_Low_version !== 1 && (
              <>
                <Button
                  type="primary"
                  size="small"
                  className="subButton smallButton marginL8"
                  onClick={() => this.handleShowAddOrDelModal(true, 1)}
                >
                  添加副柜
                </Button>
                <Button
                  type="primary"
                  size="small"
                  className="delButton smallButton marginL8"
                  onClick={() => this.handleShowAddOrDelModal(true, 2)}
                >
                  删除副柜
                </Button>
              </>
            )}
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1200 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
            rowSelection={{
              type: 'checkbox',
              ...this.rowSelection,
            }}
          />
        </Card>

        <Modal
          title="确认提示"
          visible={modalVisible}
          destroyOnClose
          onOk={this.handleConfirm}
          onCancel={() => this.handleShowModal(false, 0)}
        >
          <p>您确定要{modalTypeText[modalType][0]}吗?</p>
        </Modal>

        <Modal
          title="确认提示"
          visible={orderVisible}
          destroyOnClose
          onOk={this.handleSetIdle}
          onCancel={() => this.fetchAction('orderStatus', { body: true })}
        >
          <p>当前格口已存在未完结的订单：{unfinishedOrder}, 释放将影响此订单, 是否要继续操作?</p>
        </Modal>

        <Modal
          title="确认提示"
          visible={descVisible}
          onOk={this.handleConfimchanfgeDesc}
          onCancel={() => this.handleChangeDescModal(false)}
        >
          <p>您确定要修改格口描述为A-Z吗?</p>
        </Modal>

        <AddOrDelInfo
          addOrDelVisible={addOrDelVisible}
          detailInfo={detailInfo}
          addOrDelType={addOrDelType}
          showAddOrDelModal={this.handleShowAddOrDelModal.bind(this)}
          fetchAction={this.fetchAction.bind(this)}
        />

        <Modal
          title="确认提示"
          visible={openVisible}
          okText="打开"
          onOk={this.handleConfirmOpenCall}
          onCancel={() => this.handleOpenCellShowModal(false)}
        >
          <p>亲，开箱指令，慎操作！</p>
        </Modal>
      </Fragment>
    );
  }
}

export default Form.create<MouthDetailProps>()(MouthDetailElem);
